<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pages extends CI_Controller 
{
	protected $num_lang ;
	protected $table='tbl_page';
	// congig hinh anh
	protected $width = 800;
	protected $height = 800;
	protected $size = 800;
	protected $type ='gif|jpg|png';
	protected $patch = './upload/pages/';
	
	function __construct()
	{
		parent::__construct();		
		$this->load->model('Mpages');
		$this->load->model('Mpages_cat');
		$this->load->model('Msetting');
		$this->num_lang = $this->Msetting->get_lang();
   		$this->load->library('pagination');
    	$this->load->library('form_validation');
	 	session_start();
		if ( !isset($_SESSION['row_number']))
			$_SESSION['row_number']= 12;
			
	// check login
	check_login();
	}
	
	function index($id=0,$page='')
	{
	
		$limit = $_SESSION['row_number'];

		$config['base_url'] = site_url().'/admin/pages/index/'.$id.'/';

		$config['first_link'] = 'First';

		$config['last_link'] = 'Last';

		$config['next_link'] = '&gt;&gt;';

		$config['prev_link'] = '&lt;&lt;';

		$config['cur_tag_open'] = '<a href="#" class="current">';

		$config['cur_tag_close'] = '</a>';

		$config['uri_segment'] = 4;

		$config['num_links'] = 2;

		$config['total_rows'] = $this->Mpages->count_by_cat($id);

		$config['per_page'] = $limit;
		

		$this->pagination->initialize($config);

    if (empty($page))	$page = 0; //default value

    $data['result'] = $this->Mpages->list_data($id,$page,$limit);// $this->Muser->user_review($page, $limit);
	//print_r($data['result']);
	$cat_title  =  $this->Mpages_cat->get_title($id);
    $data['title'] ='Quản lý trang '.$cat_title['cat_name'];//$this->lang->line('title_pages_review');

    $data['page'] = str_replace('&nbsp;', '', $this->pagination->create_links());

    $data['main'] = 'pages_review';

    $this->load->view('admin/layout/template_main', $data);
	}
	// ** delete images **/
	function deleteimage($cat,$id)
	{
		$data = $this->Mpages->info_detail($id,$this->table);
		if($data != "")
		{
			$set = array('page_image'=>"");
			$path = "./upload/pages/".$data['page_image'];
			if(@file_exists($path))
				@unlink($path);
			$this->Mpages->update($set,$id,1);
			echo "<script> alert('Xóa hình thành công');window.location='".base_url()."/index.php/admin/pages/update/".$cat."/".$id."'</script>";
		}
		
	}
	//***********update  *************//
	
	function update($cat,$id)
	{
		if ($this->input->post('update'))
		{
			if($this->num_lang >1)
				 $this->form_validation->set_rules('title_en', 'Tên tiêu đề tiếng Anh', 'required');
			$this->form_validation->set_rules('title_vi', 'Tên tiêu đề', 'required');
			$this->form_validation->set_rules('cate', 'Chủ đề', 'greater_than[0]');
			if ($this->form_validation->run() == false )
				$data['missing'] = $this->form_validation->_error_array;
			else
			{	
				$tes_img  = $this->upload_file($id);
				if(!$tes_img)
				{	
					$data['missing']['img']= $this->upload->display_errors() ." Width <= ".$this->width.", Height <= ".$this->height.", Size <= ".$this->size ;	
				}
				else
				{
					if( $_FILES['img']['error'] != 4 )
					{
						$file = $this->Mpages->info_from_id($id,'tbl_page');
						$path = $this->patch.$file[0]['page_image'];
						if(@file_exists($path))
							@unlink($path);
					}
					if ($this->form_validation->run() && $this->sub_update())
					{
						echo "<script>";
						echo "alert('Cập nhật thành công');";
						echo "window.location='".base_url()."/index.php/admin/pages/update/".$cat."/".$id."'";
						echo "</script>";
					}
						
					else
						$data['missing'] = $this->form_validation->_error_array;
				}
			}
		}
    	else if ($this->input->post('close'))
			redirect('admin/pages/index/'.$cat, 'refresh');
		//reload template
		$data['cat'] = load_pages_cat();	
		$data['num_lang'] = $this->num_lang;
		$data['result']= $this->Mpages->info_form_id($id);
	    $data['title'] =  $this->lang->line('title_pages_update');
		$data['main'] = 'pages_update';
		$this->load->view('admin/layout/template_main', $data);
	}
	function sub_update()
	{
		if(isset($_POST["update"]))
		{
			$id= $this->uri->segment(5);
			$info =array(
							"vi" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),
						);
			$full =array(
							"vi" => htmlentities($this->input->post("detailed_content_vi"),ENT_QUOTES,"UTF-8"),
						);
			$info_en = array ("en" => htmlentities($this->input->post("direction_en"),ENT_QUOTES,"UTF-8"),);
			$full_en= array ("en" => htmlentities($this->input->post("detailed_content_en"),ENT_QUOTES,"UTF-8"),);
			$cate =  $this->input->post("cate");
			$modify = time();
			$status =$this->input->post("status");					
				$status =$this->input->post("status");
				$data = array(
								"page_name" => htmlentities($this->input->post("title_vi"), ENT_QUOTES, 'UTF-8'),
								"page_name_en" => htmlentities($this->input->post("title_en"), ENT_QUOTES, 'UTF-8'),
								"page_content" =>serialize($full),
								"page_content" =>serialize($full_en),
								"page_info"=> serialize($info),
								"page_info_en"=> serialize($info_en),
								"page_cat" =>$cate,
								"page_status" =>$status,
								'page_modify'=>$modify,	
								"page_image" => $_POST['img']	
							);
		if($this->Mpages->update($data,$id,1))
				return true;
			else
				return false;

		}
		else
			return false;
	}
	
	function create($id=0)
	{
		if ($this->input->post('create'))
    	{
			if($this->num_lang >1)
    			$this->form_validation->set_rules('title_en', 'English Name', 'required');
     	 	$this->form_validation->set_rules('title_vi', 'Vietnamese Name', 'required');
	     	$this->form_validation->set_rules('cate', 'Chủ đề', 'greater_than[0]');
			$tes_img  = $this->upload_file();
			
		 	if ($this->form_validation->run() == false )
				$data['missing'] = $this->form_validation->_error_array;
			else
			{
				$tes_img  = $this->upload_file();
				if(!$tes_img)
				{	
					$data['missing']['img']= $this->upload->display_errors() ." Width <= ".$this->width.", Height <= ".$this->height.", Size <= ".$this->size ;	
				}
				else
				{
 		 			if ($this->form_validation->run() && $this->sub_create())
					{
						echo "<script>";
						echo "alert('Tạo mới thành công');";
						echo "window.location='".base_url()."/index.php/admin/pages/index/".$id."'";
						echo "</script>";
					}
     	 			else
        				$data['missing'] = $this->form_validation->_error_array;		
	   			} 
			}
		 }
		elseif ($this->input->post('close'))
		{
			redirect('admin/pages/index/'.$id, 'refresh');
		}
		$data['num_lang'] = $this->num_lang;
		$data['cat'] = load_pages_cat();	
		$data['main'] = 'pages_create';
    	$data['title'] =  $this->lang->line('title_pages_create');
		$this->load->view('admin/layout/template_main', $data);
	}
	function sub_create()
	{
		if(isset($_POST["create"]))
		{	
			$cate =  $this->input->post("cate");
			$pageid = $this->Mpages->get_last_id();
			if(!isset($pageid['page_id']))
				$pid = 1;
			else
				$pid =$pageid['page_id']+1;
			$modify = time();
			$info =array(
							"vi" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),
						);
			$full =array(

							"vi" => htmlentities($this->input->post("detailed_content_vi"),ENT_QUOTES,"UTF-8"),
						);
			$info_en = array ("en" => htmlentities($this->input->post("direction_en"),ENT_QUOTES,"UTF-8"),);
			$full_en= array ("en" => htmlentities($this->input->post("detailed_content_en"),ENT_QUOTES,"UTF-8"),);

			$data = array(
							"page_name" => htmlentities($this->input->post("title_vi"), ENT_QUOTES, 'UTF-8'),
							"page_name_en" => htmlentities($this->input->post("title_en"), ENT_QUOTES, 'UTF-8'),
							"page_info" => serialize($info),
							"page_info_en" => serialize($info_en),
							"page_content" => serialize($full),
							"page_image" => $_POST['img'],
							"page_id" => $pid,
							//'page_lang'=>'1',
							'page_cat'=>$cate,
							'page_modify'=>$modify,	
						);
			if($this->Mpages->insert($data))
				return true;
			else
				return false;
		}
		else
			return false;
	}
//upload file
	function upload_file($id="",$input_file = 'img')
 	{
		if($id!="")
		{
			$file = $this->Mpages->info_from_id($id,$this->table);	
			$_POST['img'] = $file[0]["page_image"];
		}
		else
		{
			$_POST["img"]= "";	
		}
    	if ($_FILES[$input_file]['error'] == 0  )
    	{
      		$path_directory = $this->patch;
      		if ( ! is_dir($path_directory))
				mkdir($path_directory);
      		$config['upload_path'] = $path_directory;
			$config['allowed_types'] = $this->type;
			$config['max_size'] = $this->size;
			$config['max_width'] = $this->width;
			$config['max_height'] = $this->height;
      		$this->load->library('upload',$config);
      		if ($this->upload->do_upload($input_file))
      		{
        		$info_file = $this->upload->data();
        		$file_path = $info_file['file_name'];
      			$_POST['img'] = $file_path;
      		}
	 		else
	  		{
		  		return false;
	  		}
    	}
		return true;
  	}
//$***** ****	
	function request($id)

	{

		//determine 'action'
	 

		$require = array('show', 'delete');

		foreach ($_POST as $key=>$value)
		{
			if (in_array($key, $require))
				$act = $key;
		}
		//process 'action'

		if (! empty($act))

		{

			switch ($act)

			{

				case 'show': //show

				{
				
					$_SESSION['row_number'] = $this->input->post('row_number');
					
				} break;



				case 'delete': //delete

				{

					$this->Mpages->delete();

				} break;

			}//end switch



			redirect('admin/pages/index/'.$id, 'refresh');

		}//end if

	}
	public function delete($cat,$id)
	{
		if($id > 0)
			$this->Mpages->del_item($id);
		redirect('admin/pages/index/'.$cat, 'refresh');
	}
}

?>
